// Service Worker - 后台脚本处理核心逻辑

// 存储管理
class StorageManager {
  constructor() {
    this.STORAGE_KEYS = {
      recordings: 'scribehow_recordings',
      activeRecording: 'scribehow_active_recording',
      settings: 'scribehow_settings'
    };
  }

  async get(key) {
    const result = await chrome.storage.local.get(key);
    return result[key];
  }

  async set(key, value) {
    await chrome.storage.local.set({ [key]: value });
  }

  async remove(key) {
    await chrome.storage.local.remove(key);
  }
}

// 录制管理器
class RecordingManager {
  constructor() {
    this.storage = new StorageManager();
    this.activeTabId = null;
    this.isRecording = false;
    this.currentRecording = null;
  }

  async startRecording(tabId) {
    this.activeTabId = tabId;
    this.isRecording = true;
    this.currentRecording = {
      id: Date.now().toString(),
      tabId: tabId,
      title: 'New Recording',
      url: '',
      startTime: new Date().toISOString(),
      steps: []
    };

    await this.storage.set(this.storage.STORAGE_KEYS.activeRecording, this.currentRecording);
    
    // 注入内容脚本到当前标签页
    await this.injectContentScript(tabId);
    
    // 通知内容脚本开始录制
    chrome.tabs.sendMessage(tabId, {
      action: 'START_RECORDING',
      recordingId: this.currentRecording.id
    });

    return this.currentRecording;
  }

  async stopRecording() {
    if (!this.isRecording || !this.currentRecording) {
      return null;
    }

    this.isRecording = false;
    this.currentRecording.endTime = new Date().toISOString();

    // 保存录制到历史记录
    const recordings = await this.storage.get(this.storage.STORAGE_KEYS.recordings) || [];
    recordings.unshift(this.currentRecording);
    await this.storage.set(this.storage.STORAGE_KEYS.recordings, recordings);

    // 清除活动录制
    await this.storage.remove(this.storage.STORAGE_KEYS.activeRecording);

    // 通知内容脚本停止录制
    if (this.activeTabId) {
      chrome.tabs.sendMessage(this.activeTabId, {
        action: 'STOP_RECORDING'
      });
    }

    const recording = this.currentRecording;
    this.currentRecording = null;
    this.activeTabId = null;

    return recording;
  }

  async addStep(step) {
    if (!this.isRecording || !this.currentRecording) {
      return false;
    }

    // 添加时间戳和步骤编号
    step.timestamp = new Date().toISOString();
    step.stepNumber = this.currentRecording.steps.length + 1;

    this.currentRecording.steps.push(step);
    await this.storage.set(this.storage.STORAGE_KEYS.activeRecording, this.currentRecording);

    return true;
  }

  async captureScreenshot(tabId, highlightRect = null, sidebarWidth = 0) {
    try {
      // 捕获可见区域的截图
      const screenshot = await chrome.tabs.captureVisibleTab(null, {
        format: 'png',
        quality: 100
      });

      // 如果需要高亮显示元素或裁剪侧边栏，发送到内容脚本处理
      if (highlightRect || sidebarWidth > 0) {
        return new Promise((resolve) => {
          chrome.tabs.sendMessage(tabId, {
            action: 'PROCESS_SCREENSHOT',
            screenshot: screenshot,
            highlightRect: highlightRect,
            sidebarWidth: sidebarWidth
          }, (response) => {
            if (chrome.runtime.lastError) {
              console.error('Failed to process screenshot:', chrome.runtime.lastError);
              resolve(screenshot); // 返回原始截图
            } else {
              resolve(response?.processedScreenshot || screenshot);
            }
          });
        });
      }

      return screenshot;
    } catch (error) {
      console.error('Failed to capture screenshot:', error);
      return null;
    }
  }

  async injectContentScript(tabId) {
    try {
      // 先检查内容脚本是否已经注入
      const [result] = await chrome.scripting.executeScript({
        target: { tabId: tabId },
        func: () => window.scribeHowInjected
      });
      
      if (result?.result) {
        console.log('Content script already injected, skipping...');
        return;
      }
      
      // 注入脚本
      await chrome.scripting.executeScript({
        target: { tabId: tabId },
        files: ['src/content/content-script.js']
      });

      await chrome.scripting.insertCSS({
        target: { tabId: tabId },
        files: ['src/content/content-styles.css']
      });
    } catch (error) {
      console.error('Failed to inject content script:', error);
    }
  }

  async getRecordings() {
    return await this.storage.get(this.storage.STORAGE_KEYS.recordings) || [];
  }

  async deleteRecording(recordingId) {
    const recordings = await this.getRecordings();
    const filteredRecordings = recordings.filter(r => r.id !== recordingId);
    await this.storage.set(this.storage.STORAGE_KEYS.recordings, filteredRecordings);
  }

  async updateRecording(recordingId, updates) {
    const recordings = await this.getRecordings();
    const index = recordings.findIndex(r => r.id === recordingId);
    
    if (index !== -1) {
      recordings[index] = { ...recordings[index], ...updates };
      await this.storage.set(this.storage.STORAGE_KEYS.recordings, recordings);
      return recordings[index];
    }
    
    return null;
  }
}

// 导出管理器
class ExportManager {
  constructor() {
    this.formats = {
      markdown: this.exportToMarkdown.bind(this),
      html: this.exportToHTML.bind(this),
      json: this.exportToJSON.bind(this)
    };
  }

  async export(recording, format) {
    if (!this.formats[format]) {
      throw new Error(`Unsupported format: ${format}`);
    }

    return await this.formats[format](recording);
  }

  async exportToMarkdown(recording) {
    let content = `# ${recording.title}\n\n`;
    content += `**URL:** ${recording.url}\n`;
    content += `**Date:** ${new Date(recording.startTime).toLocaleString()}\n\n`;
    content += `## Steps\n\n`;

    recording.steps.forEach((step, index) => {
      content += `### Step ${index + 1}: ${step.action}\n\n`;
      content += `${step.description}\n\n`;
      
      if (step.screenshot) {
        content += `![Step ${index + 1}](${step.screenshot})\n\n`;
      }
      
      if (step.selector) {
        content += `> **Element:** \`${step.selector}\`\n\n`;
      }
    });

    return {
      content: content,
      filename: `${recording.title.replace(/[^a-z0-9]/gi, '_').toLowerCase()}.md`,
      mimeType: 'text/markdown'
    };
  }

  async exportToHTML(recording) {
    let content = `<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>${recording.title}</title>
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 800px; margin: 0 auto; padding: 40px 20px; }
    h1 { color: #1a1a1a; }
    .step { margin: 30px 0; padding: 20px; background: #f8f9fa; border-radius: 8px; }
    .step h3 { margin-top: 0; color: #5c6bc0; }
    .step img { max-width: 100%; border: 2px solid #e0e0e0; border-radius: 4px; margin-top: 10px; }
    .selector { font-family: monospace; background: #e8eaf6; padding: 2px 6px; border-radius: 3px; }
  </style>
</head>
<body>
  <h1>${recording.title}</h1>
  <p><strong>URL:</strong> <a href="${recording.url}">${recording.url}</a></p>
  <p><strong>Date:</strong> ${new Date(recording.startTime).toLocaleString()}</p>
  
  <h2>Steps</h2>
`;

    recording.steps.forEach((step, index) => {
      content += `
  <div class="step">
    <h3>Step ${index + 1}: ${step.action}</h3>
    <p>${step.description}</p>
    ${step.screenshot ? `<img src="${step.screenshot}" alt="Step ${index + 1}">` : ''}
    ${step.selector ? `<p><small>Element: <span class="selector">${step.selector}</span></small></p>` : ''}
  </div>
`;
    });

    content += `
</body>
</html>`;

    return {
      content: content,
      filename: `${recording.title.replace(/[^a-z0-9]/gi, '_').toLowerCase()}.html`,
      mimeType: 'text/html'
    };
  }

  async exportToJSON(recording) {
    return {
      content: JSON.stringify(recording, null, 2),
      filename: `${recording.title.replace(/[^a-z0-9]/gi, '_').toLowerCase()}.json`,
      mimeType: 'application/json'
    };
  }

  async download(exportData) {
    // 使用Data URL代替Blob URL，Service Worker中不支持URL.createObjectURL
    const dataUrl = `data:${exportData.mimeType};charset=utf-8,${encodeURIComponent(exportData.content)}`;

    await chrome.downloads.download({
      url: dataUrl,
      filename: exportData.filename,
      saveAs: true
    });
  }
}

// 初始化管理器
const recordingManager = new RecordingManager();
const exportManager = new ExportManager();

// 消息处理
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  (async () => {
    try {
      switch (request.action) {
        case 'START_RECORDING':
          const recording = await recordingManager.startRecording(sender.tab?.id || request.tabId);
          sendResponse({ success: true, recording });
          break;

        case 'STOP_RECORDING':
          const stoppedRecording = await recordingManager.stopRecording();
          sendResponse({ success: true, recording: stoppedRecording });
          break;

        case 'ADD_STEP':
          const stepAdded = await recordingManager.addStep(request.step);
          sendResponse({ success: stepAdded });
          break;

        case 'CAPTURE_SCREENSHOT':
          const screenshot = await recordingManager.captureScreenshot(
            sender.tab?.id || request.tabId,
            request.highlightRect,
            request.sidebarWidth
          );
          sendResponse({ success: true, screenshot });
          break;

        case 'GET_RECORDINGS':
          const recordings = await recordingManager.getRecordings();
          sendResponse({ success: true, recordings });
          break;

        case 'DELETE_RECORDING':
          await recordingManager.deleteRecording(request.recordingId);
          sendResponse({ success: true });
          break;

        case 'UPDATE_RECORDING':
          const updated = await recordingManager.updateRecording(request.recordingId, request.updates);
          sendResponse({ success: true, recording: updated });
          break;

        case 'EXPORT_RECORDING':
          const exportData = await exportManager.export(request.recording, request.format);
          if (request.download) {
            await exportManager.download(exportData);
          }
          sendResponse({ success: true, exportData });
          break;

        case 'GET_RECORDING_STATE':
          sendResponse({ 
            success: true, 
            isRecording: recordingManager.isRecording,
            currentRecording: recordingManager.currentRecording
          });
          break;

        default:
          sendResponse({ success: false, error: 'Unknown action' });
      }
    } catch (error) {
      console.error('Error handling message:', error);
      sendResponse({ success: false, error: error.message });
    }
  })();

  return true; // 保持消息通道开放
});

// 监听标签页关闭，自动停止录制
chrome.tabs.onRemoved.addListener(async (tabId) => {
  if (recordingManager.activeTabId === tabId && recordingManager.isRecording) {
    await recordingManager.stopRecording();
  }
});

// 监听扩展安装或更新
chrome.runtime.onInstalled.addListener(async (details) => {
  if (details.reason === 'install') {
    // 首次安装，设置默认配置
    const storage = new StorageManager();
    await storage.set(storage.STORAGE_KEYS.settings, {
      autoCapture: true,
      highlightColor: '#ff5252',
      captureDelay: 500,
      language: 'en'
    });
  }
});
